<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>代码格式化工具 - 在线工具集合</title>
    <script src="../utils/toast.js"></script>
    <link rel="stylesheet" href="../utils/styles.css">
    <!-- Prettier 核心库和解析器 -->
    <script src="https://unpkg.com/prettier@2.7.1/standalone.js"></script>
    <script src="https://unpkg.com/prettier@2.7.1/parser-babel.js"></script>
    <script src="https://unpkg.com/prettier@2.7.1/parser-html.js"></script>
    <script src="https://unpkg.com/prettier@2.7.1/parser-css.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #0f0c29, #302b63, #24243e);
            min-height: 100vh;
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .container {
            width: 100%;
            max-width: 900px;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: 16px;
            padding: 2rem;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
        }

        .header {
            text-align: center;
            margin-bottom: 2rem;
        }

        .header h1 {
            font-size: 2.5rem;
            background: linear-gradient(45deg, #00ff88, #00b4d8);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            margin-bottom: 0.5rem;
        }

        .formatter-section {
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
        }

        .input-group {
            display: flex;
            flex-direction: column;
            gap: 0.8rem;
        }

        textarea {
            width: 100%;
            min-height: 200px;
            padding: 1rem;
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 8px;
            color: white;
            font-family: 'Fira Code', monospace;
            resize: vertical;
        }

        .toolbar {
            display: flex;
            gap: 1rem;
            flex-wrap: wrap;
        }

        .file-input-wrapper {
            position: relative;
            overflow: hidden;
            flex: 1;
        }

        .file-input-wrapper input[type="file"] {
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            width: 100%;
            height: 100%;
            cursor: pointer;
        }

        .file-input-label {
            display: block;
            padding: 0.8rem 1.5rem;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 8px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            text-align: center;
            cursor: pointer;
            transition: background 0.3s;
        }

        .file-input-label:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        select {
            padding: 0.8rem;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 8px;
            color: white;
            flex: 1;
        }

        .action-btn {
            padding: 0.8rem 1.5rem;
            background: linear-gradient(45deg, #00ff88, #00b4d8);
            border: none;
            border-radius: 8px;
            color: #1a1a1a;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s;
        }

        .action-btn:disabled {
            opacity: 0.7;
            cursor: not-allowed;
            background: #666;
        }

        .output-container {
            position: relative;
        }

        #copyBtn {
            position: absolute;
            right: 10px;
            top: 10px;
            padding: 0.5rem 1rem;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: white;
            border-radius: 6px;
            cursor: pointer;
        }

        @media (max-width: 768px) {
            .container {
                padding: 1rem;
            }
            
            .toolbar {
                flex-direction: column;
            }
            
            .file-input-label,
            select,
            .action-btn {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <a href="../index.html" style="color: #00ff88; text-decoration: none; margin-bottom: 1rem; display: block;">← 返回首页</a>
        
        <div class="header">
            <h1>代码格式化工具</h1>
            <p>支持 JavaScript、HTML、CSS 和更多代码格式</p>
        </div>

        <div class="formatter-section">
            <div class="input-group">
                <label for="inputCode">输入代码：</label>
                <textarea id="inputCode" placeholder="粘贴代码或上传文件..."></textarea>
            </div>

            <div class="toolbar">
                <div class="file-input-wrapper">
                    <input type="file" id="fileInput" accept=".js,.jsx,.ts,.html,.css,.scss">
                    <label class="file-input-label" for="fileInput">选择文件</label>
                </div>
                
                <select id="languageSelect">
                    <option value="auto">自动检测</option>
                    <option value="babel">JavaScript</option>
                    <option value="html">HTML</option>
                    <option value="css">CSS</option>
                </select>
                
                <button class="action-btn" id="formatBtn">格式化代码</button>
            </div>

            <div class="input-group output-container">
                <label>格式化结果：</label>
                <textarea id="outputCode" readonly></textarea>
                <button id="copyBtn">复制</button>
            </div>
        </div>
    </div>

    <script>
        // DOM 元素
        const inputCode = document.getElementById('inputCode');
        const outputCode = document.getElementById('outputCode');
        const fileInput = document.getElementById('fileInput');
        const languageSelect = document.getElementById('languageSelect');
        const formatBtn = document.getElementById('formatBtn');
        const copyBtn = document.getElementById('copyBtn');

        // Prettier 配置
        const prettierConfig = {
            printWidth: 80,
            tabWidth: 2,
            useTabs: false,
            semi: true,
            singleQuote: true,
            trailingComma: 'es5',
            plugins: [
                prettierPlugins.babel,
                prettierPlugins.html,
                prettierPlugins.css
            ]
        };

        // 文件上传处理
        fileInput.addEventListener('change', async () => {
            const file = fileInput.files[0];
            if (!file) return;

            try {
                const content = await readFile(file);
                inputCode.value = content;
                detectLanguage(file);
                toast.success(`已加载文件: ${file.name}`);
            } catch (error) {
                toast.error('文件读取失败');
            }
        });

        // 格式化处理
        formatBtn.addEventListener('click', async () => {
            const code = inputCode.value.trim();
            if (!code) return toast.error('请输入要格式化的代码');

            formatBtn.disabled = true;
            formatBtn.textContent = '格式化中...';

            try {
                const parser = await detectParser(code);
                const formatted = prettier.format(code, {
                    ...prettierConfig,
                    parser
                });
                
                outputCode.value = formatted;
                toast.success('格式化成功');
            } catch (error) {
                console.error('Formatting Error:', error);
                toast.error(`格式化失败: ${error.message}`);
            } finally {
                formatBtn.disabled = false;
                formatBtn.textContent = '格式化代码';
            }
        });

        // 复制功能
        copyBtn.addEventListener('click', () => {
            outputCode.select();
            document.execCommand('copy');
            toast.success('已复制到剪贴板');
        });

        /********************
         * 工具函数
         ​********************/
        
        // 读取文件内容
        function readFile(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = (e) => resolve(e.target.result);
                reader.onerror = reject;
                reader.readAsText(file);
            });
        }

        // 检测文件类型
        function detectLanguage(file) {
            const ext = file.name.split('.').pop().toLowerCase();
            const typeMap = {
                js: 'babel',
                jsx: 'babel',
                ts: 'babel',
                html: 'html',
                css: 'css',
                scss: 'css'
            };
            languageSelect.value = typeMap[ext] || 'auto';
        }

        // 自动检测代码类型
        async function detectParser(code) {
            if (languageSelect.value !== 'auto') {
                return languageSelect.value;
            }

            // HTML 检测
            if (/<\/?[a-z][\s\S]*>/i.test(code)) return 'html';
            
            // CSS 检测
            if (/(?:^|[^{}]){[\s\S]*?}/.test(code) && 
                /:[^;]+;/.test(code)) return 'css';
            
            // 默认返回 JavaScript
            return 'babel';
        }
    </script>
</body>
</html>